package com.jdew.thkj.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.ScrollView;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.bingoogolapple.baseadapter.BGABaseAdapterUtil;
import okhttp3.MediaType;
import okhttp3.RequestBody;

import static android.content.Context.TELEPHONY_SERVICE;

/**
 * author：peixianzhong.
 * date：2016/12/8 11:43.
 * function：正则工具
 */
public class RegexValidateUtils {
    static boolean flag = false;
    static String regex = "";
    static String REGEX_CHINESE = "[\u4e00-\u9fa5]";// 中文正则


    private RegexValidateUtils() {
        throw new UnsupportedOperationException("cannot be instantiated");
    }

    public static boolean check(String str, String regex) {
        try {
            Pattern pattern = Pattern.compile(regex);
            Matcher matcher = pattern.matcher(str);
            flag = matcher.matches();
        } catch (Exception e) {
            flag = false;
        }
        return flag;
    }

    /**
     * 验证非空（为空false，不为空true）
     *
     * @param notEmputy 被验证的字符串
     */
    public static boolean checkNotEmputy(String notEmputy) {
        regex = "^\\s*$";
        return !check(notEmputy, regex);
    }

    /**
     * 验证邮箱 是:返回true 否:返回false
     *
     * @param email 被验证的字符串
     */
    public static boolean checkEmail(String email) {
        String regex = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
        return check(email, regex);
    }

    /**
     * 验证手机号码 是:返回true 否:返回false
     *
     * @param cellphone 被验证的字符串
     */
    public static boolean checkCellphone(String cellphone) {
        String regex = "^((13[0-9])|(14[0-9])|(15([0-9]))|(19[0-9])|(18[0-9])|(17[0-9])|(16[0-9]))\\d{8}$";
        return check(cellphone, regex);
    }

    /**
     * 验证固话号码 是:返回true 否:返回false
     *
     * @param telephone 被验证的字符串
     */
    public static boolean checkTelephone(String telephone) {
        String regex = "^(0\\d{2}-\\d{8}(-\\d{1,4})?)|(0\\d{3}-\\d{7,8}(-\\d{1,4})?)$";
        return check(telephone, regex);
    }

    /**
     * 验证传真号码 是:返回true 否:返回false
     *
     * @param fax 被验证的字符串
     */
    public static boolean checkFax(String fax) {
        String regex = "^(0\\d{2}-\\d{8}(-\\d{1,4})?)|(0\\d{3}-\\d{7,8}(-\\d{1,4})?)$";
        return check(fax, regex);
    }

    /**
     * 验证QQ号码 是:返回true 否:返回false
     *
     * @param QQ 被验证的字符串
     */
    public static boolean checkQQ(String QQ) {
        String regex = "^[1-9][0-9]{4,} $";
        return check(QQ, regex);
    }

    /**
     * 检测是否有emoji表情（有表情true，没有表情false）
     *
     * @param source 被验证的字符串
     */
    public static boolean checkEmoji(String source) {
        int len = source.length();
        for (int i = 0; i < len; i++) {
            char codePoint = source.charAt(i);
            if (!isEmojiCharacter(codePoint)) { //如果不能匹配,则该字符是Emoji表情
                return true;
            }
        }
        return false;
    }

    /**
     * 判断是否是Emoji,比较的单个字符
     *
     * @param codePoint 被验证的字符串
     */
    private static boolean isEmojiCharacter(char codePoint) {
        return (codePoint == 0x0) || (codePoint == 0x9) || (codePoint == 0xA) ||
                (codePoint == 0xD) || ((codePoint >= 0x20) && (codePoint <= 0xD7FF)) ||
                ((codePoint >= 0xE000) && (codePoint <= 0xFFFD)) || ((codePoint >= 0x10000)
                && (codePoint <= 0x10FFFF));
    }

    /**
     * 只能输入数字和字母  是:返回true 否:返回false
     *
     * @param password 被验证的字符串
     */
    public static boolean checkNumberLetter(String password) {
        String regex = "[LoginBean-Z,a-z,0-9]*";
        return check(password, regex);
    }

    /**
     * 密码校验(不能输入特殊字符)是:返回true 否:返回false
     *
     * @param password 被验证的字符串
     */
    public static boolean checkPassword(String password) {
        String regex = "^([\\u4e00-\\u9fa5]+|[a-zA-Z0-9]+)$";
        return check(password, regex);
    }

    /**
     * 只能输入数字  是:返回true 否:返回false
     *
     * @param password 被验证的字符串
     */
    public static boolean checkNumber(String password) {
        String regex = "^[0-9]*$";
        return check(password, regex);
    }

    /**
     * 是否为指定长度的字符串 是:返回true 否:返回false
     *
     * @param string    被验证的字符串
     * @param minLength 指定最小长度
     * @param maxLength 指定最大长度
     */
    public static boolean isBetweenMinAndMax(String string, int minLength, int maxLength) {
        if (minLength <= 0 || maxLength <= 0) {
            throw new IllegalArgumentException("MinLength Or MaxLength Is Must Big Then 0");
        }
        if (minLength > maxLength) {
            throw new IllegalArgumentException("MaxLength Is Must Big Then MinLength");
        }
        String regex = ".{" + minLength + "," + maxLength + "}";
        return check(string, regex);
    }

    /**
     * 是否为Url 是:返回true 否:返回false
     *
     * @param stringurl 被验证的字符串
     */
    public static boolean isUrl(String stringurl) {
        String url = "http://([\\w-]+\\.)+[\\w-]+(/[\\w-./?%&=]*)?";
        return check(stringurl, url);
    }

    /**
     * 是否全部是中文 是:返回true 否:返回false
     *
     * @param string 被验证的字符串
     */
    public static boolean isChineseOnly(String string) {
        String chinese = "[\\u4e00-\\u9fa5]+";
        return check(string, chinese);
    }

    /**
     * 验证是否含有特殊的字符(^%&',;=?$\") 是:返回true 否:返回false
     *
     * @param string 被验证的字符串
     */
    public static boolean isHasSoecialChar(String string) {
        String character = "[^%&',;=?$\\x22]+";
        return check(string, character);
    }

    /**
     * 格式化手机号（111****1234）
     *
     * @param string 格式化的字符串
     */
    public static String isPhone(String string) {
        String str = string.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
        return str;
    }

    public static String NoHanzi(String str) {
        String reg = "[\u4e00-\u9fa5]";

        Pattern pat = Pattern.compile(reg);

        Matcher mat = pat.matcher(str);

        String repickStr = mat.replaceAll("");
        return repickStr;
    }

    //一键复制
    public static void copyText(Context context, CharSequence textCopy) {
        if (android.os.Build.VERSION.SDK_INT > 11) {
            android.content.ClipboardManager c = (android.content.ClipboardManager) context
                    .getSystemService(Context.CLIPBOARD_SERVICE);
            c.setText(textCopy);

        } else {
            android.text.ClipboardManager c = (android.text.ClipboardManager) context
                    .getSystemService(Context.CLIPBOARD_SERVICE);
            c.setText(textCopy);
        }
    }

    // 两次点击按钮之间的点击间隔不能少于1000毫秒
    private static final int MIN_CLICK_DELAY_TIME = 2000;
    private static long lastClickTime;

    public static boolean isFastClick() {
        boolean flag = false;
        long curClickTime = System.currentTimeMillis();
        if ((curClickTime - lastClickTime) >= MIN_CLICK_DELAY_TIME) {
            flag = true;
        }
        lastClickTime = curClickTime;
        return flag;
    }

    /**
     * 判断手机是否安装某个应用
     *
     * @param context
     * @param appPackageName 应用包名
     * @return true：安装，false：未安装
     */
    public static boolean isApplicationAvilible(Context context, String appPackageName) {
        PackageManager packageManager = context.getPackageManager();// 获取packagemanager
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (appPackageName.equals(pn)) {
                    return true;
                }
            }
        }
        return false;
    }


    public static boolean checkHasInstalledApp(@NonNull Context context, String pkgName) {
        PackageManager pm = context.getPackageManager();
        boolean app_installed;
        try {
            pm.getPackageInfo(pkgName, PackageManager.GET_GIDS);
            app_installed = true;
        } catch (PackageManager.NameNotFoundException e) {
            app_installed = false;
        } catch (RuntimeException e) {
            app_installed = false;
        }
        return app_installed;
    }

    public static void fix() {       //解决oppo手机java.util.concurrent.TimeoutException: android.os.BinderProxy.finalize() timed out after 120 seconds BUG,大部分为OPPO手机
        try {
            Class clazz = Class.forName("java.lang.Daemons$FinalizerWatchdogDaemon");

            Method method = clazz.getSuperclass().getDeclaredMethod("stop");
            method.setAccessible(true);

            Field field = clazz.getDeclaredField("INSTANCE");
            field.setAccessible(true);

            method.invoke(field.get(null));

        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

    public static String topaixu(String s) {
        char[] b = s.toCharArray();
        Arrays.sort(b);
        String str2 = String.copyValueOf(b);
        return str2;
    }

    public static String ASCIISort(String str) {
        char[] test = new char[str.length()];
        StringBuilder sb = new StringBuilder();
        while (true) {
            String a = str;
            for (int i = 0; i < str.length(); i++) {
                test[i] = a.charAt(i);
            }
            Arrays.sort(test);
            for (int i = 0; i < test.length; i++) {
                sb.append(test[i]);
            }
            String trim = sb.toString();
            return trim;
        }
    }

    public static String getUniquePsuedoID() {
        String serial = null;

        String m_szDevIDShort = "35" +
                Build.BOARD.length() % 10 + Build.BRAND.length() % 10 +

                Build.CPU_ABI.length() % 10 + Build.DEVICE.length() % 10 +

                Build.DISPLAY.length() % 10 + Build.HOST.length() % 10 +

                Build.ID.length() % 10 + Build.MANUFACTURER.length() % 10 +

                Build.MODEL.length() % 10 + Build.PRODUCT.length() % 10 +

                Build.TAGS.length() % 10 + Build.TYPE.length() % 10 +

                Build.USER.length() % 10; //13 位

        try {
            serial = android.os.Build.class.getField("SERIAL").get(null).toString();
            //API>=9 使用serial号
            return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
        } catch (Exception exception) {
            //serial需要一个初始化
            serial = "serial";
        }
        //使用硬件信息拼凑出来的15位号码
        return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
    }

    public static String getRandom10() {
        String strRand = "";
        for (int i = 0; i < 10; i++) {
            strRand += String.valueOf((int) (Math.random() * 10));
        }

        return strRand;
    }

    public static String getTime13() {

        long time = System.currentTimeMillis();

        String str13 = String.valueOf(time);

        return str13;
    }

    public static String removeNonBmpUnicode(String str) {
        if (str == null) {
            return null;
        }
        str = str.replaceAll("[^\\u0000-\\uFFFF]", "");
        return str;
    }

    /**
     * 把十六进制Unicode编码字符串转换为中文字符串
     */
    public static String unicodeToString(String str) {
        Pattern pattern = Pattern.compile("(\\\\u(\\p{XDigit}{2,4}))");
        Matcher matcher = pattern.matcher(str);
        char ch;
        while (matcher.find()) {
            ch = (char) Integer.parseInt(matcher.group(2), 16);
            str = str.replace(matcher.group(1), ch + "");
        }
        return str;
    }
    /**
     * 把中文字符串转换为十六进制Unicode编码字符串
     */
    public static String stringToUnicode(String str) {
        str = (str == null ? "" : str);
        String tmp;
        StringBuffer sb = new StringBuffer(1000);
        char c;
        int i, j;
        sb.setLength(0);
        for (i = 0; i < str.length(); i++) {
            c = str.charAt(i);
            sb.append("\\u");
            j = (c >>>8); //取出高8位
            tmp = Integer.toHexString(j);
            if (tmp.length() == 1)
                sb.append("0");
            sb.append(tmp);
            j = (c & 0xFF); //取出低8位
            tmp = Integer.toHexString(j);
            if (tmp.length() == 1)
                sb.append("0");
            sb.append(tmp);

        }
        return (new String(sb));
    }

    public static boolean isAppInstalled(Context context, String uri) {
        PackageManager pm = context.getPackageManager();
        boolean installed = false;
        synchronized (context) {
            try {
                pm.getPackageInfo(uri, PackageManager.GET_SIGNATURES);
                installed = true;
            } catch (PackageManager.NameNotFoundException e) {
                installed = false;
            }
            return installed;
        }
    }

    public static String noChinese(String str) {
        Pattern pat = Pattern.compile(REGEX_CHINESE);
        Matcher mat = pat.matcher(str);
        return mat.replaceAll("");
    }

    public static Bitmap returnBitmap(String url) {
        Bitmap bm = null;
        try {
            URL iconUrl = new URL(url);
            URLConnection conn = iconUrl.openConnection();
            HttpURLConnection http = (HttpURLConnection) conn;
            int length = http.getContentLength();
            conn.connect();
            // 获得图像的字符流
            InputStream is = conn.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is, length);
            bm = BitmapFactory.decodeStream(bis);
            bis.close();
            is.close();// 关闭流
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bm;
    }

    /**
     * view 转 BitMap
     *
     * @param v 需要转换的view
     * @return
     */
    public static Bitmap getBitmapByView(View v) {
        v.setDrawingCacheEnabled(true);
        v.buildDrawingCache();
        Bitmap bitmap = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Bitmap.Config.RGB_565);
        v.setDrawingCacheEnabled(false);
        v.destroyDrawingCache();
        Canvas c = new Canvas(bitmap);
        Drawable bgDrawable = v.getBackground();
        if (bgDrawable != null) {
            bgDrawable.draw(c);
        } else {
            c.drawColor(Color.WHITE);
        }
        v.draw(c);
        Log.d("草拟吗天天OOM", bitmap.getRowBytes() + "K");
        return bitmap;
    }
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    public static String getFilePathFromUri(Uri uri) {
        if (uri == null) {
            return null;
        }

        String scheme = uri.getScheme();
        String filePath = null;
        if (TextUtils.isEmpty(scheme) || TextUtils.equals(ContentResolver.SCHEME_FILE, scheme)) {
            filePath = uri.getPath();
        } else if (TextUtils.equals(ContentResolver.SCHEME_CONTENT, scheme)) {
            String[] filePathColumn = {MediaStore.MediaColumns.DATA};
            Cursor cursor = BGABaseAdapterUtil.getApp().getContentResolver().query(uri, filePathColumn, null, null, null);
            if (cursor != null) {
                if (cursor.moveToFirst()) {
                    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                    if (columnIndex > -1) {
                        filePath = cursor.getString(columnIndex);
                        File file = new File(filePath);
                    }
                }
                cursor.close();
            }
        }
        return filePath;
    }

    /**

     ** 文件上传参数转换
     * @param value 传入值
     * @return 返回值
     */
    public static RequestBody toRequestBody(String value) {
        RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain"), value);
        return requestBody;
    }
    public static Bitmap getbitmap(String imageUri) {
        // 显示网络上的图片
        Bitmap bitmap = null;
        try {
            URL myFileUrl = new URL(imageUri);
            HttpURLConnection conn = (HttpURLConnection) myFileUrl
                    .openConnection();
            conn.setDoInput(true);
            conn.connect();
            InputStream is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);
            is.close();

        } catch (OutOfMemoryError e) {
            e.printStackTrace();
            bitmap = null;
        } catch (IOException e) {
            e.printStackTrace();
            bitmap = null;
        }
        return bitmap;
    }
    /**
     * string转bitmap
     */
    public static Bitmap stringToBitmap(String string) {
        Bitmap bitmap = null;
        try {
            byte[] bitmapArray;
            bitmapArray = android.util.Base64.decode(string, Base64.DEFAULT);
            bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0,
                    bitmapArray.length);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }
    public static void saveBmp2Gallery(Context context,Bitmap bmp) {
        String fileName = null;
        //系统相册目录
        String galleryPath = Environment
                .getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsolutePath();
        // 声明文件对象
        File file = null;
        // 声明输出流
        FileOutputStream outStream = null;
        try {
            // 如果有目标文件，直接获得文件对象，否则创建一个以filename为名称的文件
            file = new File(galleryPath, System.currentTimeMillis() + ".jpg");
            // 获得输出流，如果文件中有内容，追加内容
            outStream = new FileOutputStream(file);
            if (null != outStream) {
                bmp.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
            }
            Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            Uri uri = Uri.fromFile(file);
            intent.setData(uri);
            context.sendBroadcast(intent);
        } catch (Exception e) {
            e.getStackTrace();
        } finally {
            try {
                if (outStream != null) {
                    outStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}